package com.ophiux.cs.application.consult.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.consult.dto.CSLoginRequest;
import com.ophiux.cs.application.consult.dto.CSLoginResponse;
import com.ophiux.cs.application.consult.service.ICSUserLoginAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.domain.consult.model.aggregate.CSUserInfo;
import com.ophiux.cs.domain.consult.model.entity.CSUser;
import com.ophiux.cs.domain.consult.model.valueobj.CSUserLoginResult;
import com.ophiux.cs.domain.consult.repositories.IUserInfoRepository;
import com.ophiux.utils.exception.OphiuxRepositoryException;

/**
 * 咨询用户登录
 * @author chenh
 *
 */
@Service("cSUserLoginAppService")
public class CSUserLoginAppService implements ICSUserLoginAppService{

	@Autowired
	IUserInfoRepository cSUserInfoRepository;	//用户信息仓储
	
	@Override
	public Result<CSLoginResponse> CSLogin(CSLoginRequest request) {
		
		Result<CSLoginResponse> result = null;
		
		/**参数合法性验证**/
		if(!request.isParamValid()) {
			return Result.fail("", "参数不合法");
		}
		
		//根据账号获取用户信息
		String targetAcc = request.getTARGET_ACC();
		CSUserInfo csUserInfo = null;
		try {
			csUserInfo = cSUserInfoRepository.getCSUserInfoByTargetID(targetAcc);
		} catch (OphiuxRepositoryException e) {
			e.printStackTrace();
			return Result.fail("", e.getExceptionMessage());
		}
		
		//执行登录
		CSUserLoginResult loginResult = csUserInfo.login("", "");
		
		//判断登录结果
		if(loginResult.loginSuccess()) {
			CSLoginResponse resp = 
					new CSLoginResponse(loginResult.getTarget_id(), loginResult.getLogin_token());
			result = Result.success(resp);
			
			//保存登录信息
			try {
				cSUserInfoRepository.save(csUserInfo);
			} catch (OphiuxRepositoryException e) {
				e.printStackTrace();
				return Result.fail("", e.getExceptionMessage());
			}
			
		}else {
			result = Result.fail(loginResult.getError_code(), loginResult.getError_message());
		}
		
		return result;
	}

	
}
